package leetcode

fun main(args: Array<String>) {

    val node = ListNode(1)
    printNode(rotateRight(node, 1))
}

fun rotateRight(head: ListNode?, k: Int): ListNode? {

    if (head == null || k == 0) return head
    var len = 0
    var header = head
    var tail = head
    while (header != null) {
        len++
        header = header.next
    }

    val m = k % len

    //如果和链表长度一样，直接返回原链表
    if (m ==0)return head

    header = head
    var dist = 0
    while (dist < m - 1) {
        tail = tail?.next
        dist++
    }

    //寻找第 len - k-1 个节点 ，直接把tail移动到尾部，header，然后让tail 链接到head
    var prevHeader = header
    while (tail?.next != null) {
        prevHeader = header
        header = header?.next
        tail = tail.next
    }

    prevHeader?.next = null
    tail?.next = head
    return header

}